import {
  removeToken,
  setToken,
  getToken
} from '@/utils/auth'

import {
  setStorage,
  getStorage,
  removeStorage
} from '@/utils/storage'

import { getMenuListAPI, loginAPI } from '@/api/user'
import { constantRoutes } from '@/router'

// 本地用户信息的键
const key = 'slwl-userinfo-key'

const state = {
  token: getToken() || '',
  userInfo: getStorage(key) || {},
  routes: constantRoutes
}

const mutations = {
  setToken (state, token) {
    state.token = token
    setToken(token)
  },
  removeToken (state) {
    state.token = ''
    removeToken()
  },
  setUserInfo (state, userInfo) {
    state.userInfo = userInfo
    setStorage(key, userInfo)
  },
  removeUserInfo (state) {
    state.userInfo = {}
    removeStorage(key)
  },
  setRoutes (state, asyncRoutes) {
    state.routes = [
      ...constantRoutes,
      ...asyncRoutes
    ]
  }
}
/**
 * 递归处理菜单
 * @param {array} menuList 菜单列表
 */
const parseRoutes = (menuList) => {
  return menuList.map(route => {
    if (route.children) {
      parseRoutes(route.children)
    } else {
      delete route.children
    }
    return route
  })
}
const actions = {
  async loginAction ({ commit }, loginForm) {
    // 发登录请求
    const {
      user: userInfo,
      token: { token }
    } = await loginAPI(loginForm)
    // 提交mutation
    commit('setToken', token)
    commit('setUserInfo', userInfo)
  },
  async getRoutesAction ({ commit }) {
    const menuList = await getMenuListAPI()
    commit('setRoutes', parseRoutes(menuList))
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
